// 顶点着色器
const vertexShaderSource = `
    attribute vec4 aPosition;
    attribute vec4 aColor;
    uniform mat4 uModelMatrix;
    varying vec4 vColor;
    void main() {
        gl_Position = uModelMatrix * aPosition;
        vColor = aColor;
    }
`;

// 片元着色器
const fragmentShaderSource = `
    precision mediump float;
    varying vec4 vColor;
    void main() {
        gl_FragColor = vColor;
    }
`;

// 创建着色器方法
function createShader(gl, type, source) {
    const shader = gl.createShader(type);
    gl.shaderSource(shader, source);
    gl.compileShader(shader);
    
    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
        console.error('着色器编译失败: ' + gl.getShaderInfoLog(shader));
        gl.deleteShader(shader);
        return null;
    }
    return shader;
}

// 初始化WebGL
function initWebGL() {
    const canvas = document.createElement('canvas');
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    document.getElementById('app').appendChild(canvas);
    
    const gl = canvas.getContext('webgl');
    if (!gl) {
        console.error('WebGL不可用');
        return;
    }
    
    // 创建着色器程序
    const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
    const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
    const program = gl.createProgram();
    gl.attachShader(program, vertexShader);
    gl.attachShader(program, fragmentShader);
    gl.linkProgram(program);
    
    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
        console.error('程序链接失败: ' + gl.getProgramInfoLog(program));
        return;
    }
    
    // 立方体顶点
    const vertices = new Float32Array([
        // 前面
        -0.5, -0.5,  0.5,  1.0, 0.0, 0.0,
         0.5, -0.5,  0.5,  1.0, 0.0, 0.0,
         0.5,  0.5,  0.5,  1.0, 0.0, 0.0,
        -0.5,  0.5,  0.5,  1.0, 0.0, 0.0,
        // 后面
        -0.5, -0.5, -0.5,  0.0, 1.0, 0.0,
         0.5, -0.5, -0.5,  0.0, 1.0, 0.0,
         0.5,  0.5, -0.5,  0.0, 1.0, 0.0,
        -0.5,  0.5, -0.5,  0.0, 1.0, 0.0,
    ]);
    
    // 顶点索引
    const indices = new Uint8Array([
        0, 1, 2,   0, 2, 3,  // 前
        1, 5, 6,   1, 6, 2,  // 右
        5, 4, 7,   5, 7, 6,  // 后
        4, 0, 3,   4, 3, 7,  // 左
        3, 2, 6,   3, 6, 7,  // 上
        4, 5, 1,   4, 1, 0   // 下
    ]);
    
    // 创建缓冲区
    const vertexBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
    
    const indexBuffer = gl.createBuffer();
    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
    gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
    
    const aPosition = gl.getAttribLocation(program, 'aPosition');
    const aColor = gl.getAttribLocation(program, 'aColor');
    const uModelMatrix = gl.getUniformLocation(program, 'uModelMatrix');
    
    gl.vertexAttribPointer(aPosition, 3, gl.FLOAT, false, 24, 0);
    gl.vertexAttribPointer(aColor, 3, gl.FLOAT, false, 24, 12);
    gl.enableVertexAttribArray(aPosition);
    gl.enableVertexAttribArray(aColor);

    // 启用深度测试
    gl.enable(gl.DEPTH_TEST);
    
    let angle = 0;
    function render() {
        // 清除画布
        let viewportSize = Math.min(canvas.width, canvas.height) / 2;
        let x = (canvas.width - viewportSize) / 2;
        let y = (canvas.height - viewportSize) / 2;
        gl.viewport(x, y, viewportSize, viewportSize);
        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
        gl.clearColor(0.0, 0.0, 0.0, 1.0);
        
        // 计算模型矩阵
        // 绕Y轴旋转矩阵
        const rotationY = new Float32Array([
            Math.cos(angle), 0, Math.sin(angle), 0,
            0, 1, 0, 0,
            -Math.sin(angle), 0, Math.cos(angle), 0,
            0, 0, 0, 1
        ]);
        
        // 绕X轴旋转矩阵
        const rotationX = new Float32Array([
            1, 0, 0, 0,
            0, Math.cos(angle), -Math.sin(angle), 0,
            0, Math.sin(angle), Math.cos(angle), 0,
            0, 0, 0, 1
        ]);
        
        // 将两个旋转矩阵相乘
        const modelMatrix = new Float32Array(16);
        for (let i = 0; i < 4; i++) {
            for (let j = 0; j < 4; j++) {
                let sum = 0;
                for (let k = 0; k < 4; k++) {
                    sum += rotationX[i * 4 + k] * rotationY[k * 4 + j];
                }
                modelMatrix[i * 4 + j] = sum;
            }
        }
        
        gl.useProgram(program);
        gl.uniformMatrix4fv(uModelMatrix, false, modelMatrix);
        
        // 绘制立方体
        gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_BYTE, 0);
        
        angle += 0.01;
        requestAnimationFrame(render);
    }
    
    render();
}

// 页面加载完成后初始化WebGL
window.onload = initWebGL;
